package cn.xinfei.xdecision.conf;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationNotAllowedException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Map;

@Slf4j
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }


    public static <T> T getBean(String beanName, Class<T> clzz) {
        try {
            T bean = getApplicationContext().getBean(beanName, clzz);
            return bean;
        } catch (BeanCreationNotAllowedException e) {
            log.warn("getBean error={}", e.getMessage());
        } catch (Exception e) {
            log.error("getBean error={}", e.getMessage(), e);
        }
        return null;
    }

    public static <T> Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> clzz) {
        try {
            return getApplicationContext().getBeansWithAnnotation(clzz);
        } catch (Exception e) {
            log.error("getBean error={},clzz={}", e.getMessage(),clzz, e);
        }
        return null;
    }
    public static <T> T getBean(Class<T> clzz) {
        try {
            return getApplicationContext().getBean(clzz);
        } catch (Exception e) {
            log.error("getBean error={},clzz={}", e.getMessage(),clzz, e);
        }
        return null;
    }
}